/**消息监听类 */
export class MessageCenter {

    private point: number = 0;
    private dict: { [key: string]: any[]; } = {}; //字典

    public constructor() {

    }

    /**
     * 添加消息监听
     * @param type 消息唯一标识
     * @param listener 侦听函数
     * @param listenerObj 侦听函数所属对象
     */
    public addListener(type: string, listener: Function, listenerObj: any) {
        let arr = this.dict[type];
        //若为空则初始为空数组
        if (arr == null || arr == undefined) {
            this.dict[type] = arr = [];
        }else {
            this.dict[type] = arr = arr.concat();
        }
        //检测是否已存在
        for(let key of arr) {
            if(key[0] == listener && key[1] == listenerObj) {
                return;
            }
        }
        arr.push([listener,listenerObj]);
    }

    /**
     *  移除消息监听
     * @param type 消息唯一标识
     * @param listener 侦听函数
     * @param listenerObj 侦听函数所属对象
     */

    public removeListener(type: string, listener: Function, listenerObj: any) {
        let arr = this.dict[type];
        if (arr == null || arr == undefined) {
            return;
        }else {
            this.dict[type] = arr = arr.concat();
        }
        let len = arr.length;
        for(let i = len - 1; i >= 0; i--) {
            let item = arr[i];
            if(item[0] == listener && item[1] == listenerObj) {
                arr.splice(i,1);
                break;
            }
        }
        //若当前长度为0则移除整个消息
        if(len == 0) {
            this.dict[type] = null;
            delete this.dict[type];
        }
    }

    /**
     * 触发消息
     * @param type 消息唯一标识
     * @param param 消息参数
     */
    public dispatch (type:string,...param:any[]) {
        let listeners = this.dict[type];
        if(listeners == null || listeners == undefined) {
            return;
        }
        if(listeners.length == 0) {
            return;
        }
        this.point++;
        for(let item of listeners) {
            //执行消息对应的方法
            item[0].apply(item[1],param);
        }
        this.point--;
    }

}

